package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.jsf.FacesContextUtils;

import com.builder.FamiliaBuilder;
import com.dao.BaseModelDAO;
import com.model.Familia;
import com.query.FamiliaQuery;
import com.util.JSFUtil;
import com.view.FamiliaView;

@ManagedBean
@ViewScoped
@SuppressWarnings("serial")
public class FamiliaController extends PaginableController<Familia> {

	private Logger log = Logger.getLogger(FamiliaController.class);
	private BaseModelDAO<Familia> dao;
	private Familia familia;
	private FamiliaQuery familiaQuery;
	private List<FamiliaView> listaFamilia;

	@ManagedProperty("#{familiaView}")
	private FamiliaView familiaView;

	@ManagedProperty("#{familiaBuilder}")
	private FamiliaBuilder familiaBuilder;

	@SuppressWarnings("unchecked")
	public FamiliaController() {
		try {
			dao = (BaseModelDAO<Familia>) FacesContextUtils
					.getWebApplicationContext(FacesContext.getCurrentInstance())
					.getBean("familiaDAO");
			familiaQuery = new FamiliaQuery();
			addEdit = false;

		} catch (Throwable e) {
			log.error("Error al inicializar la clase FamiliaController", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	@PostConstruct
	private void init() {
		listaFamilia = familiaBuilder.toView(dao.getList());
	}

	public void query(ActionEvent event) {
		loadList();
	}

	public void edit(ActionEvent event) {
		try {
			familia = (Familia) lazyDM.getRowData();
			familia = dao.findFULL(familia.getID());
			familiaView = familiaBuilder.toView(familia);
			listaFamilia = familiaBuilder.toView(dao.getList());
			// saco la familia que se está modificando
			listaFamilia.remove(familiaView);
			addEdit = true;

		} catch (Throwable e) {
			log.error("Error al editar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void delete(ActionEvent event) {
		try {
			familia = (Familia) lazyDM.getRowData();
			dao.delete(familia);
			loadList();
		} catch (Throwable e) {
			log.error("Error al eliminar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void add(ActionEvent event) {
		addEdit = true;
		clear();
	}

	public void save(ActionEvent event) {
		try {
			familia = familiaBuilder.toDomain(familiaView);

			if (familia.getID() != null) {
				dao.edit(familia);
				addEdit = false;
			} else {
				dao.save(familia);
			}
			clear();
			JSFUtil.saveMessage("Elemento guardado con exito",
					FacesMessage.SEVERITY_INFO);
			if (!addEdit) {
				loadList();
			}
		} catch (DataIntegrityViolationException e) {
			JSFUtil.saveMessage(
					"Error al guardar: La descripcion debe ser unica en el sistema.",
					FacesMessage.SEVERITY_ERROR);
		} catch (Throwable e) {
			log.error("Error al guardar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void cancel(ActionEvent event) {
		addEdit = false;
		lazyDM = null;
	}

	public void clear() {
		familia = new Familia();
		familiaView = new FamiliaView();
		listaFamilia = familiaBuilder.toView(dao.getList());
	}

	private void loadList() {

		lazyDM = new LazyDataModel<Familia>() {
			@Override
			public List<Familia> load(int first, int pageSize,
					String sortField, SortOrder sortOrder,
					Map<String, Object> filters) {

				Map<String, Object> filtro = new HashMap<String, Object>();
				filtro.put("descripcion", familiaQuery.getDescripcion());
				return dao.getList(first, pageSize, "descripcion", true,
						filtro, true);
			}
		};

		Map<String, Object> filtro = new HashMap<String, Object>();
		filtro.put("descripcion", familiaQuery.getDescripcion());
		lazyDM.setRowCount(dao.count(filtro, true).intValue());
	}

	public BaseModelDAO<Familia> getDao() {
		return dao;
	}

	public void setDao(BaseModelDAO<Familia> dao) {
		this.dao = dao;
	}

	public Familia getFamilia() {
		return familia;
	}

	public void setFamilia(Familia familia) {
		this.familia = familia;
	}

	public FamiliaQuery getFamiliaQuery() {
		return familiaQuery;
	}

	public void setFamiliaQuery(FamiliaQuery familiaQuery) {
		this.familiaQuery = familiaQuery;
	}

	public FamiliaView getFamiliaView() {
		return familiaView;
	}

	public void setFamiliaView(FamiliaView familiaView) {
		this.familiaView = familiaView;
	}

	public FamiliaBuilder getFamiliaBuilder() {
		return familiaBuilder;
	}

	public void setFamiliaBuilder(FamiliaBuilder familiaBuilder) {
		this.familiaBuilder = familiaBuilder;
	}

	public List<FamiliaView> getListaFamilia() {
		return listaFamilia;
	}

	public void setListaFamilia(List<FamiliaView> listaFamilia) {
		this.listaFamilia = listaFamilia;
	}

}
